import React, { Component, Fragment } from 'react';
import { connect } from 'dva';
import router from 'umi/router';
import styles from './expressBillModal.less';
import moment from 'moment';
import { Input, Select, Checkbox,Radio,Modal, Form, Button, message, Spin,Row, Col, Table, InputNumber } from 'antd';
//import { checkStatus } from '@/utils/CommonRequestOption';

const FormItem = Form.Item;
const { Option } = Select;

export default class Index extends Component{
  
  state={
    selectedIds:[],
    deliverWay:1,
    listNum:[],
    selectedListNum:[],
    foot:{footer:null},
    ItemList:[],
    oemInfo:{},
    expressBillInfo:{},
    required:true,
    validateStatusList:[],
    printLoading:false,
    clickBtn1:false,
    clickBtn2:false 
  }

  componentDidMount(){
    window.Isoption = true;
    const {list,form, expressListLoading,oemInfo,expressList,expressBillList,addressList,onRef,PrintedCourierBillList} = this.props;
    const { validateStatusList } = this.state;    
    onRef&&onRef(this)
    list.forEach(v=>{
        validateStatusList.push('success')
        if(PrintedCourierBillList&&PrintedCourierBillList.length){
           v.WaybillNumber=PrintedCourierBillList[0].WaybillNumber;
        } 
    })      
    this.setState({
        validateStatusList,
        ItemList:JSON.parse(JSON.stringify(list)), 
        oemInfo,         
    })
    if(PrintedCourierBillList&&PrintedCourierBillList.length){
        form.setFieldsValue({
              addressId:PrintedCourierBillList[0].StoreAddressId,
              expressId:PrintedCourierBillList[0].ExpressId
        });
        setTimeout(()=>{
          this.selectExpress(PrintedCourierBillList[0].ExpressId)
        }, 300);
     }      
  }

  componentWillMount() {
    window.Isoption = false;
  }

  okHandle = () => {
    const {form,comfirm,list} = this.props;
    const { selectedIds ,listNum,selectedListNum,ItemList,oemInfo,expressBillInfo,sendInfo,validateStatusList} = this.state;  
    form.validateFields((err,values)=>{
        console.log(values)
        if(!values.expressBillId||!values.addressId||!values.expressId) return;
        for(let i=0;i<ItemList.length;i++){ 
            //console.log(!ItemList[i].WaybillNumber,ItemList[i].WaybillNumber)
            ItemList[i].oemInfo=oemInfo;
            ItemList[i].expressBillInfo=expressBillInfo;
            ItemList[i].TemplateWidth=expressBillInfo.TemplateWidth;
            ItemList[i].TemplateHeight=expressBillInfo.TemplateHeight;
            ItemList[i].sendInfo=sendInfo;
            ItemList[i].printDate=moment(Date.now()).format("YYYY-MM-DD hh:mm:ss");                         
            if(!ItemList[i].WaybillNumber){
                validateStatusList[i]='error';
                this.setState({
                    validateStatusList
                })
              return;
            }    
          }    
           console.log(ItemList)
           this.setState({
            ItemList,
            printLoading:true,
            clickBtn1:false,
            clickBtn2:true           
           })

           let arr=[];
           ItemList.forEach(v=>{
            arr.push({OrderId:v.Id,ExpressId:values.expressId,WaybillNumber:v.WaybillNumber});
           })
           let params={        
            storeAddressId:values.addressId,
            ItemList:ItemList,
            items:arr     
          };
          //console.log(params,777)
          //return;
          if(typeof comfirm === 'function') comfirm(params)
          
    })        
  }
  

  handleModalVisible = () => {
    const { handleModalVisible } =this.props;
    if(typeof handleModalVisible === 'function') handleModalVisible();
  }

  changeDeliverNum = (e,record,index) => {
    const { ItemList} = this.state;      
    console.log(e)
    if(ItemList.length){                   
        ItemList[index].WaybillNumber=e.target.value;       
        this.setState({
            ItemList
        })
    }
    this.checkStatus(e.target.value,index)
   
  }

  setFirstNum = (e) =>{
    const { ItemList} = this.state;
      let value=e.target.value;
    if(ItemList.length){       
        ItemList&&ItemList.forEach((item,index)=>{
            if(index==0){
                item.WaybillNumber=value;
            }else{
                item.WaybillNumber=++value;
            }          
        })                    
        this.setState({
            ItemList
        })
    }
    //this.checkStatus(e.target.value,index)
    console.log(value)
  }

  selectExpress = (e)=>{
    const { ItemList} = this.state;
    const {expressList} = this.props;    
    console.log(e)
    if(ItemList.length){       
        ItemList&&ItemList.forEach(item=>{
            let index=expressList.findIndex(v=>v.Id==e);
            if(index>-1){
                item.ExpressName=expressList[index].Name; 
            }               
        })                    
        this.setState({
            ItemList
        })
    }
    
    
  }

  selectAddress = (e) => {
    //const { sendInfo} = this.state;
    const {addressList} = this.props;                  
    // for(let i=0;i<ItemList.length;i++){  
    //     let index = addressList.findIndex(v=>v.Id==e);           
    //     index>-1?ItemList[i].sendInfo=addressList[index]:'';               
    // }   
    let sendInfo={}; 
    let index = addressList.findIndex(v=>v.Id==e);           
    index>-1?sendInfo=addressList[index]:{};                
    this.setState({
        sendInfo
    })
    
    
  }

  selectExpressTemp= (e) => {
    //const { expressBillInfo} = this.state;
    const {getInfo} = this.props; 
    getInfo(e,(expressBillInfo)=>{
        this.setState({
            expressBillInfo
        })
    })        
  }

  checkStatus = (val,index) => {
      const {validateStatusList} = this.state;
      if(val){
        validateStatusList[index]='success';
      }else{
        validateStatusList[index]='error';
      }
      this.setState({
        validateStatusList
      })
  }

  printAndDelivery = () => {      
    const {form,comfirm} = this.props;
    const { selectedIds ,listNum,selectedListNum,ItemList,oemInfo,expressBillInfo,sendInfo,validateStatusList} = this.state;  
    form.validateFields((err,values)=>{
        console.log(values)
        if(!values.expressBillId||!values.addressId||!values.expressId) return;
        for(let i=0;i<ItemList.length;i++){ 
            //console.log(!ItemList[i].WaybillNumber,ItemList[i].WaybillNumber)
            ItemList[i].oemInfo=oemInfo;
            ItemList[i].expressBillInfo=expressBillInfo;
            ItemList[i].TemplateWidth=expressBillInfo.TemplateWidth;
            ItemList[i].TemplateHeight=expressBillInfo.TemplateHeight;
            ItemList[i].sendInfo=sendInfo;
            ItemList[i].printDate=moment(Date.now()).format("YYYY-MM-DD hh:mm:ss");                         
            if(!ItemList[i].WaybillNumber){
                validateStatusList[i]='error';
                this.setState({
                    validateStatusList
                })
              return;
            }    
          }    
           console.log(ItemList)
           this.setState({
            ItemList,
            printLoading:true,
            clickBtn1:true,
            clickBtn2:false            
           });
           let arr=[];
           ItemList.forEach(v=>{
            arr.push({OrderId:v.Id,ExpressId:values.expressId,WaybillNumber:v.WaybillNumber});
           })
           let params={        
            storeAddressId:values.addressId,
            ItemList:ItemList,
            items:arr     
          };

          if(typeof comfirm === 'function') comfirm(params,true)
          
    })      
  }

	render(){
    const {modalVisible,form:{getFieldDecorator},addressList,expressList,expressBillList,list,confirmLoading,addressListLoading,expressListLoading,expressBillListLoading} = this.props;
    const {selectedIds,deliverWay,listNum,foot,required,ItemList,validateStatusList,printLoading,clickBtn1,clickBtn2} = this.state;    
    const columns = [
      {
        title: '收货人',
        dataIndex: 'ReceivingName', 
        width:'20%',            
      },
      {
        title: '订单号',
        dataIndex: 'OrderNo',       
        width: '25%',
      },
      {
        title: '物流公司',
        dataIndex: 'ExpressName',      
        width: '25%',                   
      },
      {
        title: '快递单号',
        dataIndex: 'WaybillNumber',
        width: '30%',   
        render:(text,record,index) =>( 
          <FormItem validateStatus={validateStatusList[index]}>
            <Input value={record.WaybillNumber}  onChange={(e)=>this.changeDeliverNum(e,record,index)} onBlur={(e)=>this.checkStatus(e.target.value,index)}/>
          </FormItem>                  
        )       
      },
    ];

    const rowSelection = {
      selectedRowKeys: selectedIds,
      onChange: (selectedIds, selectedRows) => {
        const {listNum,selectedListNum} = this.state;
        const { list } = this.props;
        console.log(selectedIds, selectedRows)
        let arr=[];
        selectedIds.forEach((v)=>{
          let index= list.OrderItem.findIndex(item=>item.Id==v);          
          arr.push(listNum[index])
        })
        this.setState({
          selectedIds: selectedIds,
          selectedListNum:arr,
        });
      },
    };      

	return (		
      <Modal
        destroyOnClose={true}
        centered
        title="打印快递单"
        visible={modalVisible}
        onOk={this.okHandle}                
        confirmLoading={ confirmLoading }
        onCancel={this.handleModalVisible}
        width={640}  
        footer={false}
        className={`${styles.expressBillModal}`}   
      >      
          <Spin spinning={expressBillListLoading||addressListLoading||expressListLoading}>
            <div>           
                <Form  >                   
                    <Row gutter={16}>        
                    <Col span={12}>
                        <FormItem label="快递单模板" wrapperCol={{span:16}} labelCol={{span:8}}>                            
                            {
                                getFieldDecorator('expressBillId',{
                                    rules:[
                                        {required:true,message:'此项为必选项'}
                                    ]
                                })(
                                    <Select placeholder="请选择" style={{ width: '100%' }} onChange={this.selectExpressTemp} >                                
                                        {
                                            expressBillList&&expressBillList.map(item => {
                                                return <Option value={item.Id} key={item.Id}>{item.TempLateName}</Option>;
                                            })
                                        }
                                    </Select>
                                )
                            }
                        </FormItem>
                    </Col>
                    <Col span={12}>
                        <FormItem label="发货地址"  wrapperCol={{span:16}} labelCol={{span:8}} >                        
                            {
                                getFieldDecorator('addressId',{
                                    rules:[
                                        {required:true,message:'此项为必选项'}
                                    ]
                                })(
                                    <Select style={{ width: '100%' }} onChange={this.selectAddress} >
                                        {addressList &&
                                    
                                        addressList.map(item => {
                                            return <Option value={item.Id} key={item.Id}>{item.Name}</Option>;
                                        })}
                                    </Select>
                                )
                            }
                        </FormItem>
                    </Col>                              
                    </Row>
                    <Row gutter={16}>          
                    <Col span={12}>
                        <FormItem label="物流公司"  wrapperCol={{span:16}} labelCol={{span:8}} >                            
                            {
                                getFieldDecorator('expressId',{
                                    rules:[
                                        {required:true,message:'此项为必选项'}
                                    ]
                                })(
                                    <Select style={{ width: '100%' }} onChange={this.selectExpress} >
                                        {expressList &&
                                    
                                    expressList.map(item => {
                                            return <Option value={item.Id} key={item.Id}>{item.Name}</Option>;
                                        })}
                                    </Select>
                                )
                            }
                        </FormItem>
                    </Col>  
                    <Col span={12}>
                        <FormItem label="起始快递单号"  wrapperCol={{span:16}} labelCol={{span:8}}>
                            <Input style={{ width: '100%' }} onChange={this.setFirstNum} />
                        </FormItem>
                    </Col>                                        
                    </Row>                            
                </Form>
            </div>
            <Table
                //loading={loading}
                //bordered
                scroll={{ y: list.length>2?146:0 }}              
                rowKey={record => record.Id}
                dataSource={ItemList}
                columns={columns}
               // rowSelection={rowSelection}
                // onChange={this.handleStandardTableChange}
                 pagination={false}
            />   
            <div className="xkd-mt24 xkd-ml16 xkd-mb24">共{list.length}单</div> 
            <div className={styles.modalFooter}>
                <Button className="xkd-mr8" onClick={this.handleModalVisible}>取消</Button>
                {
                    ItemList&&ItemList.length&&ItemList[0].OrderStatusName==='待发货'?<Button className="xkd-mr8" onClick={this.printAndDelivery} loading={clickBtn1&&printLoading} disabled={printLoading}>打印并发货</Button>:null
                }                
                <Button type="primary" onClick={this.okHandle} loading={clickBtn2&&printLoading} disabled={printLoading}>打印</Button>
            </div>          
          </Spin>
      </Modal>
    );
	}
}